<?php
require_once 'inc.php';
?>

<style>
table, td, tr {
	border-spacing: 0px 0px;
	border:0px;
	padding:0px;
	margin:0px;
}
</style>

<?php
/*header('Content-type: image/jpeg');
$r = new ResizeImage();
$r->load($_REQUEST['f']);
$r->autoResize(300, 300, 300, 300);
$r->output();*/
//echo '<pre>';
$image_file = $_REQUEST['f'];
if (empty($image_file) || !file_exists($image_file)) exit;
$image_top_colors = get_image_top_colors($image_file);
//$image_top_colors = array_slice($image_top_colors, 1, 20, true);
echo draw_color_cube($image_top_colors, 1200, 20);
echo "<img src=".$image_file." />";

function get_image_top_colors($image_file)
{
	$image_p = imagecreatetruecolor(SAMPLE_BORDER_SIZE, SAMPLE_BORDER_SIZE);
	$image = get_image_from_file($image_file);
	if (!$image) return false;
	
	imagecopyresized($image_p, $image, 0, 0, 0, 0,
		SAMPLE_BORDER_SIZE, SAMPLE_BORDER_SIZE, imagesx($image), imagesy($image));
	imagetruecolortopalette2($image_p, false, 255);

	$hex_colors = array();
	for ($x=0; $x<SAMPLE_BORDER_SIZE; $x++)
	{
		for ($y=0; $y<SAMPLE_BORDER_SIZE; $y++)
		{
			$rgb = ImageColorsForIndex($image_p, imagecolorat($image_p, $x, $y));

			$hex_color = sprintf("%02x%02x%02x", $rgb['red'], $rgb['green'], $rgb['blue']);
			$hex_colors[hex2safe($hex_color)]++;
		}
	}
	
	arsort($hex_colors);
	
	return $hex_colors;
}


function draw_color_cube($top_colors, $width, $height)
{
	$total_count = array_sum($top_colors);

	$s = sprintf("<div style='width:%dpx; height:%dpx;'>", $width, $height);
	foreach ($top_colors as $color => $count)
	{
		$s .= sprintf("<a target=_blank href=index.php?c=%s><div style='float:left;width:%dpx; height:%dpx; background:#%s'></div></a>",
			$color, $width*$count/$total_count, $height, $color);
	}
	$s .= "</div>";

	return $s;
}
